<template>
  <div class="create-page">
    <div class="left-slide">
      <List @nodeClick="handleNodeClick" ref="structureListRef"/>
    </div>
    <div class="right-form-container">
      <div class="header-box">
        <div style="margin-top:5px">
          <div style="width: auto;display: flex">
          <el-button   type="primary" @click="addStaff">新增人员</el-button>
          <el-button  type="warning" @click="modelDownload"><span style="color: white">批量新增模版下载</span></el-button>
          </div>
          <div style="margin-top: 5px">
            <el-upload
                class="upload-demo"
                ref="upload"
                :limit="1"
                :show-file-list="true"
                :on-success="onSuccess"
                :on-error="onError"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :on-exceed="handleExceed"
                :before-remove="beforeRemove"
                :on-change="handleChange"
                :before-upload="beforeUpload"
                action="string"
                accept=".xlsx, .xls"
                :file-list="fileList"
                :auto-upload="false">
              <el-button slot="trigger"  type="primary">选取文件</el-button>
<!--              <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>-->
              <el-button  style="background: #1890ff;margin-left: 10px;" @click="addStaffBatch"><span style="color: white">批量新增</span></el-button>
              <div class="el-upload__tip" slot="tip" v-show="!fileList[0]">未选择任何文件</div>
              <div slot="tip" class="el-upload__tip">仅支持.xlsx, .xls类型文件</div>
            </el-upload>
          </div>
        </div>
        <div style="margin-top: 20px">
          <el-form size="mini" ref="searchForm" :inline="true" :model="searchForm">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="searchForm.name" placeholder="请输入姓名" />
            </el-form-item>
            <el-form-item label="工号" prop="username">
              <el-input v-model="searchForm.username" placeholder="请输入工号" />
            </el-form-item>
            <el-form-item>
              <el-button  type="primary" @click="submitForm">查询</el-button>
            </el-form-item>
            <el-form-item>
              <el-button type="info" @click="formCancel">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div class="table-container">
        <div class="table-box">
          <el-table
              :data="tableData"
              :height="'100%'"
              border
              :header-cell-style="{textAlign:'center'}"
              :cell-style="{textAlign:'center'}"
          >
            <!--            <el-table-column type="selection" />-->
            <el-table-column prop="id" label="编号" />
            <el-table-column prop="username" label="工号" />
            <el-table-column prop="name" label="姓名">
              <template slot-scope="scope">
                <el-tag>{{scope.row.name}}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="role__name" label="角色" />
            <el-table-column prop="post__name" label="岗位" />
            <el-table-column prop="persontype__name" label="人员类别" />
            <el-table-column prop="dept__name" label="部门名称" />
            <el-table-column prop="is_active" label="状态" >
              <template slot-scope="scope">
                <span :style="scope.row.is_active === true ? 'color:green':'color:red'">{{scope.row.is_active === true? '有效':'无效'}}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="240">
              <template slot-scope="scope">
                <el-button type="primary" size="mini" @click="check(scope.row)">编辑</el-button>
                <el-button :style="scope.row.is_active === true?'background-color:red':'background-color:green'" size="mini" @click="changeStatus(scope.row)">
                  <span style="color: white">{{scope.row.is_active === true?'禁用':'启用'}}</span>
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="table-pagination">
          <!-- 分页 -->
          <el-pagination
              :current-page.sync="paginations.page_index"
              :page-sizes="paginations.page_sizes"
              :page-size="paginations.page_size"
              :layout="paginations.layout"
              background
              :total="paginations.total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
    <EditStaff ref="editStaffRef" :form-data="currentRow" @callback="handleEditorCallBack"/>
  </div>
</template>
<script>
import * as XLSX from 'xlsx';
import List from '@/components/List.vue';
import {userBatchAdd,userListSelect,userStatusChange} from "@/utils/user";
import EditStaff from "@/components/EditStaff.vue";
export default {
  name: 'staffManage',
  components: {
    EditStaff,
    List
  },
  props: {},
  data() {
    return {
      lastUid: null,
      fileList:[],
      paginations: {
        page_index: 1, //当前位于哪页
        total: 0, //数据总数
        page_size: 10, //一页显示多少条
        page_sizes: [5, 10, 15, 20,50,100], //每页显示多少条
        layout: "total, sizes, prev, pager, next, jumper", //翻页属性
      },
      allTableData:[],
      tableData: [],
      searchForm: {
        name:'',
        dept_id:'',
        username:''
      },
      currentRow: null
    }
  },
  created() {},
  mounted() {
    this.getTableData();
  },
  methods: {
    //设置分页属性
    setPaginations() {
      //初始化
      this.paginations.total = this.allTableData.length;
      this.paginations.page_index = 1;
      this.paginations.page_size = 10;
      //设置默认的分页数据
      this.tableData = this.allTableData.filter((item, index) => {
        return index < this.paginations.page_size;
      });
    },
    //分页方法
    handleCurrentChange(page) {
      //获取当前页
      let index = this.paginations.page_size * (page - 1);
      //获取数据总数
      let nums = this.paginations.page_size * page;
      //容器
      let tables = [];
      for (let i = index; i < nums; i++) {
        if (this.allTableData[i]) {
          tables.push(this.allTableData[i]);
        }
        this.tableData = tables;
      }
    },
    handleSizeChange(page_size) {
      this.paginations.page_index = 1;
      this.paginations.page_size = page_size;
      this.tableData = this.allTableData.filter((item, index) => {
        return index < page_size;
      });
    },
    handleNodeClick(val) {
      this.searchForm.dept_id = val.id;
      this.getTableData();
    },
    submitForm() {
      this.getTableData();
    },
    formCancel() {
      this.searchForm = {};
    },
    check(row) {
      let temp = JSON.stringify(row)
      temp = temp.replace('role__id','role_id')
      temp = temp.replace('post__id','post_id')
      temp = temp.replace('persontype__id','persontype_id')
      temp = temp.replace('dept__id','dept_id')
      this.currentRow = JSON.parse(temp)
      this.$refs['editStaffRef'].showDialog();
    },
    handleEditorCallBack() {
      this.currentRow = null;
      this.getTableData();
      this.$refs['structureListRef'].getTreeData();
    },
    changeStatus(row) {
      this.$confirm('确定更改用户状态?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        userStatusChange({ username: row.username }).then(res => {
          if (res.code === "1") {
            this.$message({
              type: 'success',
              message: '更改用户状态成功!'
            });
          }
          this.getTableData()
        })
        // eslint-disable-next-line no-unused-vars
      }).catch(_=>{

      })
    },
    getTableData() {
      userListSelect(this.searchForm).then(res => {
        if (res.code === "1") {
          this.allTableData = res.data;
          this.setPaginations();
        }
      });
    },
    addStaff(){
       this.currentRow = null;
       this.$refs['editStaffRef'].showDialog();

    },
    exportData() {
    const data = [
        ['人资编码','姓名','人员类别','三级部门','四级部门','岗位','角色'],
        ['34000001','张三','合同制','云中台','','部门正职','普通用户'],
        ['34000002','王二','派遣制','寿县分公司','众兴农村营业部','员工','考勤员'],
        ['34000003','李四','外包人员','寿县分公司','','公司领导','普通用户'],
    ]
      const worksheet = XLSX.utils.aoa_to_sheet(data);
      const workbook = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');

      // 生成Blob数据
      const excelData = XLSX.write(workbook, { type: 'array', bookType: 'xlsx' });
      const blobData = new Blob([excelData], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });

      // 创建Blob URL
      const blobUrl = URL.createObjectURL(blobData);
      // 创建一个隐藏的<a>标签并设置href属性为Blob URL
      const link = document.createElement('a');
      link.href = blobUrl;
      link.target = '_blank';
      link.download = `人员信息导入模版.xlsx`;
      // 触发点击操作，开始下载文件
      link.click();
      // 释放Blob URL
      URL.revokeObjectURL(blobUrl);
},
    modelDownload(){
      this.exportData()
    },
    onError(){
      this.$message.error('文件上传失败')
    },
    onSuccess(){
      this.$message.success('文件上传成功')
    },
    // 导入前检查文件
    beforeUpload(file) {
      this.file = file
      const extension = file.name.split(".")[1] === "xls";
      const extension2 = file.name.split(".")[1] === "xlsx";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!extension && !extension2) {
        this.$message({
          message: "上传文件只能是 xls、xlsx格式!",
          type: "error",
        });
      }
      if (!isLt2M) {
        console.log("上传文件大小不能超过 2MB!");
        this.$message({
          message: "上传文件大小不能超过 2MB!",
          type: "error",
        });
      }
      return extension || extension2 || isLt2M;
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${fileList.length} 个文件`);
    },
    beforeRemove(file) {
      return this.$confirm(`确定移除 ${ file.name }？`);
    },
    addStaffBatch(){
      console.log(this.fileList[0].raw)
      // const data = {
      //   excelfile:this.fileList[0].raw
      // }
      // const file = new File(this.fileList[0].raw,this.fileList[0].name,{type:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",lastModified:Date.now()})
      // const formData = new FormData();
      // formData.append("excelfile", this.fileList[0].raw);
      //   const File = param.file;
      let formDataInfo = new FormData();
      formDataInfo.append("file", this.fileList[0].raw);
      userBatchAdd(formDataInfo).then(res=>{
        console.log(res)
        if(res.code==="1"){
          this.$message.success(res.message)
        }
      })
    },
    async handleChange(ev, fileList) {
      // this.fileList = fileList
      // console.log(this.fileList)
      if (fileList.length > 0) {
        this.fileList = [fileList[fileList.length - 1]]
      } else {
        this.fileList = fileList[0]
      }
      let file = ev.raw
      if (this.lastUid === file.uid) {
        return
      }
      this.lastUid = file.uid
      if (file) {
        console.log(file)
        if (
            file.name.indexOf('.xls') !== -1 ||
            file.name.indexOf('.xlsx') !== -1
        ) {
          let data = await this.readFile(file)
          let workbook = XLSX.read(data, {
            type: 'binary',
            cellDates: true
          })
          let worksheet = workbook.Sheets[workbook.SheetNames[0]]
          // eslint-disable-next-line no-unused-vars
          let secondsheet = workbook.Sheets[workbook.SheetNames[1]]
          let resultExcel = XLSX.utils.sheet_to_json(worksheet)
          let tableHead = Object.keys(resultExcel[0]);
          console.log(resultExcel, '解析后表格数据')
          console.log(tableHead, '解析后表格头')
        }
      }
    },
    readFile(file) {
      return new Promise(resolve => {
        let reader = new FileReader()
        reader.readAsBinaryString(file)
        reader.onload = ev => {
          resolve(ev.target.result)
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.create-page {
  width: 100%;
  height: 88vh;
  //max-height: 690px;
  background-color: #fff;
  display: flex;
  .left-slide {
    overflow: hidden;
    width: 45%;
    height: 100%;
    border: 10px #f0f0f0 solid;
    text-align: center;
    padding-top: 20px;
    box-sizing: border-box;
  }
  .left-slide:hover {
    overflow: auto;
  }
  .right-form-container {
    //border: 10px #f0f0f0 solid;
    width: 80%;
    height: 100%;
    border-top: 10px #f0f0f0 solid;
    border-right: 10px #f0f0f0 solid;
    border-bottom: 10px #f0f0f0 solid;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    .header-box{
      width: 100%;
      background-color: #fff;
      padding: 10px 15px;
      display:flex;
      justify-content:space-between;
      align-items:center;
      ::v-deep .el-form-item{
        //margin-right: 30px;
        .el-form-item__label{
          font-family: "Microsoft YaHei";
          color: #333
        }
      }
    }
    .table-container{
      width: 100%;
      border-top: 10px #f0f0f0 solid;
      flex: 1;
      margin-top: 10px;
      display: flex;
      flex-direction: column;
      .table-box {
        width: 100%;
        flex-grow: 1;
        overflow: hidden;
        overflow-y: auto;
        a{
          color: #409EFF;
        }
      }
      .table-pagination{
        //height: 60px;
        width: 100%;
        text-align: right;
        background-color: #fff;
        margin-top: 10px;
        display: flex;
        align-items: center;
        justify-content: flex-end;
        ::v-deep .el-pagination{
          margin-bottom: 10px;
          span, button, ul>li{
            //height: 50px;
            //line-height: 50px;
            //font-size: 16px;
          }
        }
      }
    }
  }
}
</style>
<style>
.el-upload__tip{
  color:red
}
</style>
